'use strict';

const Service = require('egg').Service;

class TopicService extends Service {

  async getTopicById(topicId) {

    const query = { _id: topicId, deleted: false };

    const topic = await this.ctx.model.Topic.findOne(query);
    
    if (!topic) {
      // throw new Error('此话题不存在或已被删除。');
      return [];
    }

    return [ topic ];
  }

  getCountByQuery(query) {
    query.deleted = false;
    return this.ctx.model.Topic.count(query).exec();
  }

  async getTopicList(query = {}, opt = {}) {
    query.deleted = false;
    const topics = await this.ctx.model.Topic.find(query,
      ['_id', 'title', 'image', 'desc', 'tag'],
      opt).exec();
      
    if (topics.length === 0) {
      return [];
    }

    return topics;
  }
  
  newAndSave(title, content, biz, image, desc, tag) {
    const topic = new this.ctx.model.Topic();
    topic.title = title;
    topic.content = content;
    topic.biz = biz;
    topic.image = image;
    topic.desc = desc;
    topic.tag = tag;
    return topic.save();
  }
}

module.exports = TopicService;
